package net.begincode.core.support;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hlj~宇晗
 * @create 2017-03-26 13:01
 **/
public class AuthInterceptor extends HandlerInterceptorAdapter {
	public static final String NOLOGIN_JSON = "{\"msg\":\"为登录或已登出，请重新登录\"}";
	public static final String NOLOGIN_MSG = "检测到您的操作处于未登录或登录时间超时状态，请重新登录。";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			AuthPassort authPassort = ((HandlerMethod) handler).getMethodAnnotation(AuthPassort.class);
			//没有声明需要权限,或者声明不验证权限validate = false
			if (authPassort == null || authPassort.validate() == false) {
				return true;
			}
			//cookie验证账号权限
			//cookie验证账户权限
			//BegincodeUser begincodeUser = CookieOperation.getUser(request);
			//if (begincodeUser != null){
			//	return true;
			//}
			//跳转到首页
			String requestType = request.getHeader("X-Requested-With");
			if (requestType == null) {
				request.getRequestURI();
				request.setAttribute("msg", NOLOGIN_MSG);
				request.getRequestDispatcher("/page/index.jsp").forward(request, response);
				return false;
			} else {
				//返回json
				response.setContentType("application/json;charset=utf-8");
				response.getWriter().write(NOLOGIN_JSON);
				response.getWriter().flush();
				return false;
			}
		}
	return true;
	}
}

